<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserLevel;
use app\models\UserBao as Model;
use yii\db\Exception;

class BaoController extends H5Controller
{
    public function actionAdd()
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $id = $this->post('id');
            $referrer = $this->user->id;
            $quantity = $this->post('quantity');

            // 被报单的人必须是 运营商
            $u = User::findOne(['id' => $id]);
            if ($u->level < UserLevel::$keys['member']) {
                throw new Exception('不能操作');
            }

            // 判断还有推荐人没
            $r = User::findOne(['id' => $referrer]);
            $model = new Model();
            if ($r->referrer_id == 0) {
                $model->is_platform = 1;
                $model->received_id = 0;
            } else {
                $model->received_id = $r->referrer_id;
            }

            // 积分处理
            // $u = User::findOne(['id' => $id]);
            $price = UserLevel::find()
                ->where(['value' => $u->level])
                ->select(['price'])
                ->scalar();
            $price_temp = UserLevel::find()
                ->where(['value' => $r->level])
                ->select(['price'])
                ->scalar();
            $model->score = $price * $quantity;
            $model->temp_score = $price_temp * $quantity;
            $account = UserAccount::findOne(['user_id' => $id]);
            $account->tmp_score += $price * $quantity;
            $account->save();
            $model->user_id = $id;
            $model->quantity = $quantity;
            $model->send_id = $referrer;
            $model->init = 1;
            $model->save();

            // 递归自动审核
            if ($model->received_id > 0) {
                $this->_auto($model);
            }

            $transaction->commit();
            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }

    }

    // 递归自动审核
    private function _auto($log)
    {
        $model = new Model();
        $r = User::findOne(['id' => $log->received_id]);
        if ($r->referrer_id == 0) {
            $model->is_platform = 1;
        } else {
            $model->received_id = $r->referrer_id;
        }
        $log->status = 1;
        $log->save();

        $u = User::findOne(['id' => $log->received_id]);
        $price = UserLevel::find()
            ->where(['value' => $u->level])
            ->select(['price'])
            ->scalar();

        $model->temp_score = $price * $log->quantity;
        $model->send_id = $log->received_id;
        $model->user_id = $log->user_id;
        $model->score = $log->score;
        $model->quantity = $log->quantity;
        $model->final_id = $log->final_id ? $log->final_id : $log->id;
        $model->save();

        if ($model->received_id > 0) {
            $this->_auto($model);
        }
    }

    // 我的审核列表
    public function actionList()
    {
        $type = intval($this->post('type'));

        $query = Model::find()
            ->where(['received_id' => $this->user->id]);


        if ($type == 1) {
            $query->andWhere(['status' => 0]);
        } else if ($type == 2) {
            $query->andWhere(['status' => 1]);
        }

        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));


        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->with(['send'])
            ->limit($pageSize)
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            if ($item['send']['nickname']) {
                $item['send']['nickname'] = base64_decode($item['send']['nickname']);
            }
        }

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    // 我的报单
    public function actionMyList()
    {
        $type = intval($this->post('type'));

        $query = Model::find()
            ->where(['send_id' => $this->user->id])
            ->andWhere(['init' => 1]);


        if ($type == 1) {
            $query->andWhere(['status' => 0]);
        } else if ($type == 2) {
            $query->andWhere(['status' => 1]);
        }

        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));


        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->with(['send', 'user'])
            ->limit($pageSize)
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            if ($item['send']['nickname']) {
                $item['send']['nickname'] = base64_decode($item['send']['nickname']);
            }
            if ($item['user']['nickname']) {
                $item['user']['nickname'] = base64_decode($item['user']['nickname']);
            }
        }

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    public function actionCheck()
    {

        return $this->fail('');

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $id = $this->post('id');
            $log = Model::findOne(['id' => $id]);

            if ($log->status == 1) {
                throw new \Exception('此单已经审核过了');
            }

            $model = new Model();
            $r = User::findOne(['id' => $log->received_id]);
            if ($r->referrer_id == 0) {
                $model->is_platform = 1;
            } else {
                $model->received_id = $r->referrer_id;
            }
            $log->status = 1;
            $log->save();
            $u = User::findOne(['id' => $log->received_id]);
            $price = UserLevel::find()
                ->where(['value' => $u->level])
                ->select(['price'])
                ->scalar();
            $model->temp_score = $price * $log->quantity;
            $model->send_id = $this->user->id;
            $model->user_id = $log->user_id;
            $model->score = $log->score;
            $model->quantity = $log->quantity;
            $model->final_id = $log->final_id ? $log->final_id : $log->id;
            $model->save();

            $transaction->commit();
            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }
    }

    // 删除审核 [ 审核列表 ]
    // 但是已经用不到了, 因为已经自动审核到平台了...
    public function actionDelete()
    {

        // return $this->fail('测试中');

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $id = $this->post('id');
            $log = Model::findOne(['id' => $id]);

            if ($log->status == -99) {
                throw new \Exception('此单已经删除了');
            }

            $log->status = -99;
            $log->final = -99;

            $log->save();
            // 删除链上的
            if ($log->final_id > 0) {
                Model::updateAll(['status' => -99, 'final' => -99], [
                    'or',
                    ['id' => $log->final_id],
                    ['final_id' => $log->final_id]
                ]);
            }

            $transaction->commit();
            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }
    }

    // 取消订单 [ 我的报单 ]
    public function actionCancel()
    {

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $id = $this->post('id');
            $log = Model::findOne(['id' => $id]);

            if ($log->status == -99) {
                throw new \Exception('此单已经取消了');
            }

            // 如果上次已经审核了
            if ($log->status == 1) {
                throw new \Exception('上级已经审核, 请联系上级删除');
            }

            $log->status = -99;
            $log->final = -99;

            $log->save();


            $transaction->commit();
            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }
    }

    public function actionSet()
    {
        $id = $this->post('id');
        $user = User::findOne(['id' => $id]);
        $user->level = UserLevel::$keys['member'];
        $user->save();

        $x = User::find()
            ->where(['id' => $id])
            ->with(['level0'])
            ->asArray()
            ->one();

        return $this->successEncode(['user' => $x]);
    }
}